package bma.common.netty.handler;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

public abstract class ChannelHandlerException extends
		SimpleChannelUpstreamHandler {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ChannelHandlerException.class);

	protected boolean handleError = false;

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		Throwable t = e.getCause();
		if (log.isDebugEnabled()) {
			log.debug("handle exception", t);
		}
		if (handleError && log.isWarnEnabled()) {
			log.warn("nest exception,skip", t);
			return;
		}
		if (!e.getChannel().isOpen()) {
			log.debug("channel closed");
			return;
		}
		try {
			handleError = true;
			exceptionHandle(ctx, t);
		} finally {
			handleError = false;
		}
	}

	protected abstract void exceptionHandle(ChannelHandlerContext ctx,
			Throwable t);

}
